package com.zbest.zpay.acctrans.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zbest.common.lang.base.Money;
import com.zbest.zpay.acctrans.common.exception.AccTransRuntimeException;
import com.zbest.zpay.acctrans.dal.mapper.AccountBalanceMapper;
import com.zbest.zpay.acctrans.dal.mapper.AccountDetailMapper;
import com.zbest.zpay.acctrans.dal.mapper.AccountInfMapper;
import com.zbest.zpay.acctrans.dal.model.AccountBalance;
import com.zbest.zpay.acctrans.dal.model.AccountDetail;
import com.zbest.zpay.acctrans.dal.model.AccountInf;
import com.zbest.zpay.acctrans.enums.biz.AcctransBizCode;
import com.zbest.zpay.acctrans.service.facade.AcctransQueryService;
import com.zbest.zpay.acctrans.service.model.MainAccountDetail;
import com.zbest.zpay.acctrans.service.model.QryMainDetailsPageRequest;
import com.zbest.zpay.acctrans.service.model.QryMainDetalsPageResponse;
import com.zbest.zpay.acctrans.service.model.QueryMainAccountBalanceRequest;
import com.zbest.zpay.acctrans.service.model.QueryMainAccountBalanceResponse;
import com.zbest.zpay.acctrans.service.model.QueryTransStateResponse;
import com.zbest.zpay.acctrans.share.InitialTransactionService;

/**
 * Created by wenfeihu on 16/5/25.
 */
@Service("acctransQueryService")
public class AcctransQueryServiceImpl implements AcctransQueryService {
    private static final Logger logger = LoggerFactory
            .getLogger(AcctransQueryServiceImpl.class);

    @Autowired
    private InitialTransactionService initialTransactionService;

    @Autowired
    private AccountInfMapper accountInfMapper;

    @Autowired
    private AccountBalanceMapper accountBalanceMapper;

    @Autowired
    private AccountDetailMapper accountDetailMapper;

    @Override
    public QueryMainAccountBalanceResponse queryMainAccountBalance(QueryMainAccountBalanceRequest queryMainAccountBalanceRequest) {
        logger.info("用户余额查询接口请求数据:"+queryMainAccountBalanceRequest.toString());
        String actDat = initialTransactionService.getActDat();
        QueryMainAccountBalanceResponse queryMainAccountBalanceResponse = new QueryMainAccountBalanceResponse();
        try {
            String usrId = queryMainAccountBalanceRequest.getUsrId();
            String actTyp = queryMainAccountBalanceRequest.getActTyp();
            String actNo = actTyp + usrId;
            AccountInf mainAccountInf = accountInfMapper.qryAccountInf(actNo);
            queryMainAccountBalanceResponse.setActNo(mainAccountInf.getActNo());
            queryMainAccountBalanceResponse.setUsrId(mainAccountInf.getUsrId());
            queryMainAccountBalanceResponse.setActNam(mainAccountInf.getActNam());
            queryMainAccountBalanceResponse.setActSts(mainAccountInf.getActSts());
            queryMainAccountBalanceResponse.setActStsw(mainAccountInf.getActStsw());
            AccountBalance mainAccountBalance = accountBalanceMapper.qryByActNo(actNo);
            if (mainAccountBalance != null) {
                Money curActBal = new Money(mainAccountBalance.getCurActBal(), Money.DEFAULT_CURRENCY);
                Money uavaBal = new Money(mainAccountBalance.getUavaBal(), Money.DEFAULT_CURRENCY);
                Money lastUavaBal = new Money(mainAccountBalance.getLastUavaBal(), Money.DEFAULT_CURRENCY);
                Money lastActBal = new Money(mainAccountBalance.getLastActBal(), Money.DEFAULT_CURRENCY);
                Money notTxAvaBal = new Money(mainAccountBalance.getNotTxAvaBal(), Money.DEFAULT_CURRENCY);
                Money stlBal = new Money(0, Money.DEFAULT_CURRENCY);
                Money bal = new Money(0, Money.DEFAULT_CURRENCY);
                String lastAcDate = mainAccountBalance.getUpdDat();
                if (Long.valueOf(lastAcDate) <= Long.valueOf(actDat)) {
                    stlBal = curActBal.subtract(uavaBal).subtract(notTxAvaBal);
                }
                bal = curActBal.subtract(uavaBal);
                queryMainAccountBalanceResponse.setBal(bal);
                queryMainAccountBalanceResponse.setCurActBal(curActBal);
                queryMainAccountBalanceResponse.setUavaBal(uavaBal);
                queryMainAccountBalanceResponse.setStlBal(stlBal);
            } else {
                Money zero = new Money(0, Money.DEFAULT_CURRENCY);
                queryMainAccountBalanceResponse.setBal(zero);
                queryMainAccountBalanceResponse.setCurActBal(zero);
                queryMainAccountBalanceResponse.setUavaBal(zero);
                queryMainAccountBalanceResponse.setStlBal(zero);
            }
            queryMainAccountBalanceResponse.setCode(AcctransBizCode.SUCCESS);
            queryMainAccountBalanceResponse.setMessage(AcctransBizCode.SUCCESS.desc());
        } catch (AccTransRuntimeException e) {
            queryMainAccountBalanceResponse.setCode(e.getBizCode());
            queryMainAccountBalanceResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("用户余额查询接口异常", e);
            queryMainAccountBalanceResponse.setCode(AcctransBizCode.SYSTEM_ERROR);
            queryMainAccountBalanceResponse.setMessage(AcctransBizCode.SYSTEM_ERROR.desc());
        }
        logger.info("用户余额查询接口响应数据:"+queryMainAccountBalanceResponse.toString());
        return queryMainAccountBalanceResponse;
    }

    @Override
    public QryMainDetalsPageResponse queryMainDetails(QryMainDetailsPageRequest qryMainDetailsPageRequest) {
        logger.info("查询主账户收支明细的请求数据:"+qryMainDetailsPageRequest.toString());
        QryMainDetalsPageResponse qryMainDetalsPageResponse=new QryMainDetalsPageResponse();
        List<MainAccountDetail> mainAccountDetails = new ArrayList<MainAccountDetail>();
        String startDat = qryMainDetailsPageRequest.getStartDat();
        String endDat = qryMainDetailsPageRequest.getEndDat();
        String usrId = qryMainDetailsPageRequest.getUsrId();
        try {
            int count = accountDetailMapper.qryDetailsCntPage(usrId, startDat, endDat);
            // mysql的start从0开始；
            List<AccountDetail> accountDetails = null;
            if (count > 0) { // 优化，如果没有订单数据，则不用查询数据库；
                final int start = (qryMainDetailsPageRequest.getPageNo() - 1)
                        * qryMainDetailsPageRequest.getItemPerPage();
                accountDetails = accountDetailMapper.qryDetailsPage(usrId,startDat, endDat, start, qryMainDetailsPageRequest.getItemPerPage());
            }

            if (!CollectionUtils.isEmpty(accountDetails)) {
                for (AccountDetail accountDetail : accountDetails) {
                    MainAccountDetail mainAccountDetail = new MainAccountDetail();
                    mainAccountDetail.setActDat(accountDetail.getActDat());
                    mainAccountDetail.setActNo(accountDetail.getActNo());
                    mainAccountDetail.setCcy(accountDetail.getCcy());
                    mainAccountDetail.setActTyp(accountDetail.getActTyp());
                    mainAccountDetail.setMainCdSts(accountDetail.getMainCdSts());
                    mainAccountDetail.setOldTxDt(accountDetail.getOldTxDt());
                    mainAccountDetail.setOldTxTm(accountDetail.getOldTxTm());
                    mainAccountDetail.setSysDat(accountDetail.getSysDat());
                    mainAccountDetail.setSysTim(accountDetail.getSysTim());
                    mainAccountDetail.setDcFlg(accountDetail.getDcFlg());
                    mainAccountDetail.setDrAmt(new Money(accountDetail.getDrAmt(),Money.DEFAULT_CURRENCY));
                    mainAccountDetail.setCrAmt(new Money(accountDetail.getCrAmt(),Money.DEFAULT_CURRENCY));
                    mainAccountDetail.setBal(new Money(accountDetail.getBal(),Money.DEFAULT_CURRENCY));
                    mainAccountDetail.setHldAmt(new Money(accountDetail.getHldAmt(),Money.DEFAULT_CURRENCY));
                    mainAccountDetail.setTxDesc(accountDetail.getTxDesc());
                    mainAccountDetail.setOrdTyp(accountDetail.getOrdTyp());
                    mainAccountDetail.setOrdNo(accountDetail.getOrdNo());
                    mainAccountDetail.setUsrId(accountDetail.getUsrId());
                    mainAccountDetails.add(mainAccountDetail);
                }
            }
            qryMainDetalsPageResponse.setTotalItem(count);
            qryMainDetalsPageResponse.setMainAccountDetails(mainAccountDetails);
            qryMainDetalsPageResponse.setCode(AcctransBizCode.SUCCESS);
            qryMainDetalsPageResponse.setMessage(AcctransBizCode.SUCCESS.desc());
        } catch (Exception e) {
            logger.error("", e);
            qryMainDetalsPageResponse.setCode(AcctransBizCode.SYSTEM_ERROR);
            qryMainDetalsPageResponse.setMessage(AcctransBizCode.SYSTEM_ERROR.desc());
        }
        logger.info("查询主账户收支明细的响应数据:" + qryMainDetalsPageResponse.toString());
        return qryMainDetalsPageResponse;
    }

    @Override
    public QueryTransStateResponse queryTransState(String ordNo) {
        return null;
    }
}
